package com.sviet.game.tetriswindow;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

import com.sviet.game.tetriswindow.util.Constants;

/**
 * @author THINHNH
 * 
 */
public class SplashActivity extends Activity implements OnClickListener {
	private String TAG = SplashActivity.class.getSimpleName();
	private Timer timer;
	public static long startTime;
	private LinearLayout ll_splash;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.v(TAG, "onCreate");

		setContentView(R.layout.activity_splash);

		ll_splash = (LinearLayout) findViewById(R.id.splash_ll_splash);
		ll_splash.setOnClickListener(this);

		startTime = System.currentTimeMillis();

		startNewActivity();
	}

	public void onResume() {
		super.onResume();
	}

	public void onDestroy() {
		super.onDestroy();

		try {
			timer.cancel();
			timer = null;
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * Go to home screen after waiting time.
	 */
	public void startNewActivity() {
		long endTime = System.currentTimeMillis();

		if (endTime - startTime >= Constants.SPLASH_WAITING_TIME) {
			Intent intent = new Intent(SplashActivity.this, TetrisActivity.class);
			startActivityForResult(intent, Constants.EXITAPP);
			finish();
		} else {

			TimerTask timerTask = new TimerTask() {

				public void run() {
					// TODO Auto-generated method stub

					Intent intent = new Intent(SplashActivity.this, TetrisActivity.class);
					startActivityForResult(intent, Constants.EXITAPP);
					finish();
				}
			};

			timer = new Timer();
			timer.schedule(timerTask, Constants.SPLASH_WAITING_TIME);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.splash_ll_splash) {
			try {
				timer.cancel();
				timer = null;
			} catch (Exception e) {
				// TODO: handle exception
			}

			Intent intent = new Intent(SplashActivity.this, TetrisActivity.class);
			startActivityForResult(intent, Constants.EXITAPP);
			finish();
		}
	}
}